package com.example.im.infra.executor.send.redis;

import com.example.im.infra.executor.send.DefaultSendExecutor;
import com.example.im.infra.executor.send.dto.MessageInfo;
import com.example.im.infra.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author PC
 * redis监听
 */
@Component
@ConditionalOnProperty(name = "cus.ws.communication-type", havingValue = "redis")
public class RedisMessageListener implements MessageListener {

    private final static Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);

    private DefaultSendExecutor defaultSendExecutor;

    @Autowired
    public void setDefaultSendExecutor(DefaultSendExecutor defaultSendExecutor) {
        this.defaultSendExecutor = defaultSendExecutor;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //消息内容
        String messageJson = new String(message.getBody(), StandardCharsets.UTF_8);
        MessageInfo messageInfo = JsonUtils.toObjectByTypeReference(messageJson, new TypeReference<MessageInfo>() {
        });
        switch (messageInfo.getScopeOfSending()) {
            case USER:
                defaultSendExecutor.sendToUser(messageInfo.getSendUserName(), messageInfo.getMessage());
                break;
            case ALL:
                defaultSendExecutor.sendToAll(messageInfo.getSendUserName(), messageInfo.getMessage());
                break;
            default:
                //一般来说不会出现该情况，除非用户覆盖了ScopeOfSending，后续可以开个扩展发送范围的口子
                logger.warn("invalid sending range:" + messageInfo.getScopeOfSending().getScopeCode());
                break;
        }
    }
}
